var userdao = require('../../../dao/userdao');
var logger = require('pomelo-logger').getLogger(__filename);
module.exports = function(app) {
	return new Handler(app);
};

var Handler = function(app) {
	this.app = app;
};

var handler = Handler.prototype;

//注册
handler.register = function (msg, session, next) {
	// var self = this;
	var uid = msg.uid;
	var pwd = msg.pwd;
	userdao.createUser(uid,pwd,function (err,player) {
		if(err || !player){
			logger.error('Create user failed! ' + err.stack);
			next(new Error('fail to create user from dao'), {
				// route: msg.route,
				code: 500
			});
			return;
		}
		next(null,{
			code:200,
			msg:player.name+'register'
		});
	})
};
// 登陆
handler.login = function(msg, session, next) {
	var self = this;
	var uid = msg.uid;
	var pwd = msg.pwd;
    var res = self.app.getServers();
    userdao.confirmUser(uid,pwd,function (err,player) {
		if(err || !player){
			logger.error('Get user for userdao failed! ' + err.stack);
			next(new Error('fail to get user from dao'), {
				// route: msg.route,
				code: 500
			});
			return;
		}
		next(null, {
			code: 200,
			msg: uid+' login',
			host: res.host,
			port: res.clientPort
		});
	})
};


handler.enter = function(msg, session, next) {
	var self = this;
	var rid = msg.rid;
	var uid = msg.username + '*' + rid;
	var sessionService = self.app.get('sessionService');

	//duplicate log in
	if( !! sessionService.getByUid(uid)) { // 意义上等价于 if(x),这种写法是为了安全
		next(null, {
			code: 500,
			error: true
		});
		return;
	}

	/**
	 * session.set：给session添加一个属性，提供用户更改session的机会。
	 * session.push： session同步，在改变session之后需要同步，以后的请求处理中就可以获取最新session。
	 * session.bind(uid)就是将session与该用户id建立一个映射关系，key -- value。
	 *
	 */
	session.bind(uid);
	session.set('rid', rid);
	session.push('rid', function(err) {
		if(err) {
			console.error('set rid for session service failed! error is : %j', err.stack);//错误处理
		}
	});

	session.set('position',null);

	session.on('closed', onUserLeave.bind(null, self.app));//事件绑定

	//put user into channel
	self.app.rpc.area.areaRemote.add(session, uid, self.app.get('serverId'), rid, true, function(users){
		next(null, {
			users:users
		});
	});
};

/**
 * User log out handler
 *
 * @param {Object} app current application
 * @param {Object} session current session object
 *
 */
//退出
var onUserLeave = function(app, session) {
	if(!session || !session.uid) {
		return;
	}
	app.rpc.area.areaRemote.kick(session, session.uid, app.get('serverId'), session.get('rid'), null);
};